package crypt

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"fmt"
)

// Encrypt 加密
func Encrypt(src string, key []byte, iv []byte) (string, error) {
	result, err := Aes128Encrypt([]byte(src), key, iv)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("%x", result), nil
}

// Decrypt 解密
func Decrypt(src string, key []byte, iv []byte) (string, error) {
	var result []byte
	var err error

	result, err = hex.DecodeString(src)
	if err != nil {
		return "", err
	}
	origData, err := Aes128Decrypt(result, key, iv)
	if err != nil {
		return "", err
	}
	return string(origData), nil
}

func Aes128Encrypt(origData, key []byte, IV []byte) ([]byte, error) {
	if key == nil || len(key) != 16 {
		return nil, nil
	}
	if IV != nil && len(IV) != 16 {
		return nil, nil
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	origData = PKCS5Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, IV[:blockSize])
	encrypted := make([]byte, len(origData))
	// 根据CryptBlocks方法的说明，如下方式初始化encrypted也可以
	blockMode.CryptBlocks(encrypted, origData)
	return encrypted, nil
}

func Aes128Decrypt(decrypted, key []byte, IV []byte) ([]byte, error) {
	if key == nil || len(key) != 16 {
		return nil, nil
	}
	if IV != nil && len(IV) != 16 {
		return nil, nil
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, IV[:blockSize])
	origData := make([]byte, len(decrypted))
	blockMode.CryptBlocks(origData, decrypted)
	origData = PKCS5UnPadding(origData)
	return origData, nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padText...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unPadding 次
	unPadding := int(origData[length-1])
	return origData[:(length - unPadding)]
}

// DecryptData 数据解密
func DecryptData(data string) (result string, err error) {
	defer func() {
		if recover() != nil {
			err = fmt.Errorf("解密失败")
		}
	}()
	// 加密密码
	key := []byte("fdf$DHsfa@fd#")
	iv := make([]byte, 16)

	result, err = Decrypt(data, key, iv)
	return
}
